package org.x.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    // 创建自定义RedisTemplate
    @Bean
    public RedisTemplate<String, Object> redisTemplate(
            RedisConnectionFactory connectionFactory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        // 设置键（key）的序列化方式 - String类型
        template.setKeySerializer(new StringRedisSerializer());

        // 设置值（value）的序列化方式 - JSON格式
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        // 设置hash键的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());

        // 设置hash值的序列化方式
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        return template;
    }
}